package com.penghaisoft.microwms.base.web.auth.controller;

import com.alibaba.fastjson.JSON;
import com.penghaisoft.microwms.base.web.auth.service.IBaseResourceService;
import com.penghaisoft.microwms.base.web.auth.service.IUserResroleService;
import com.penghaisoft.microwms.base.web.auth.service.IUserService;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseUser;
import com.penghaisoft.microwms.common.base.model.BaseUserResroleKey;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.data.model.MdModelMes;
import com.penghaisoft.microwms.common.dto.BaseUserResourceForm;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.dto.Transfer;
import com.penghaisoft.microwms.common.dto.UserMes;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.page.TurnPageInfo;
import com.penghaisoft.microwms.common.service.IMesInterfaceService;
import com.penghaisoft.microwms.common.service.MesProperties;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
//import com.haier.cosmo.base.fastdfs.FastDFSConfig;


import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;

/**
 * @Title: UserController.java
 * @Description: 用户管理restAPI
 * @author zxcq0
 * @date 2017/2/28 14:16
 * @version V1.00
 */

@RestController
@RequestMapping(value = "/auth/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserResroleService userResroleService;

    @Autowired
    private IBaseResourceService baseResourceService;
    
    @Autowired
	private IMesInterfaceService mesInterfaceService;
	
	@Resource
	private MesProperties mesProperties;

//    @Autowired
//    private FastDFSConfig fastDFSConfig;

    /** 
     * @Title querySupplyCode
     * @Description 查询当前登录人的供应商编号
     * @author luoteng
     * @date 2017年12月12日:下午4:58:09
     * @return TransResult
     */
    @PostMapping("/r/supplycode")
    public TransResult querySupplyCode() {
        TransResult result = new TransResult();
    	BaseUser user = getUserInfo();
    	result.setCode(Constant.SUCCESS);
    	result.setData(user);
        return result;
    }
    
    /**
     * @Title: UserController.java
     * @Description: 根据id查询
     * @author zxcq0
     * @date 2017/2/28 14:16
     * @param id
     * @return 
     */
    @RequestMapping(value = "/r/{id}", method = RequestMethod.POST)
    public TransResult findUserById(@PathVariable String id) {
        TransResult transResult = new TransResult();
        transResult.setCode(Constant.SUCCESS);
        BaseUser user = userService.queryById(id);
        user.setPassword("");
        transResult.setData(user);
        return transResult;
    }

    /**
     * @Description: 新增用户
     * @author zxcq0
     * @date 2017/3/1 9:49
     * @param
     * @return
     */
    @RequestMapping(value = "/c", method = RequestMethod.POST)
    public TransResult add(BaseUser user) {
    	user.setCreateBy(getLoginName());
        TransResult transResult = new TransResult();
        
        String url = mesProperties.getUrl() + "/imes-provider/system/authority/user/add/wms";
        //Mes新增
		UserMes userAdd = new  UserMes();
		userAdd.setAccount(user.getLoginName());
		userAdd.setPersonCode(user.getLoginName());
		userAdd.setPersonName(user.getUserName());
		userAdd.setMarkAble("1");//		0：无效 1：有效
		userAdd.setRemark("WMS新增");
		userAdd.setCreateUser(getLoginName());
		userAdd.setCreateUserName(getUserName());
		if(user.getPassword()==null||user.getPassword().equals("")){
			userAdd.setPassword(Constant.INIT_PWD);
		}else{
			userAdd.setPassword(user.getPassword());	
		}
		
//		调mes新增接口
		HandResp handResp = mesInterfaceService.publicWSResp(url, MediaType.APPLICATION_JSON_TYPE, JSON.toJSONString(userAdd));
		if(handResp.getCode() != null && handResp.getCode().equals("0")){
			transResult.setCode(handResp.getCode());
			transResult.setMsg(handResp.getMsg());
	        return transResult;
		}else{
			Resp resp = userService.add(user);
			
			return fromResp(resp);
		}
    }

    /**
     * @Description: 更新
     * @author zxcq0
     * @date 2017/3/2 14:55
     * @param
     * @return
     */
    @RequestMapping(value = "/u", method = RequestMethod.POST)
    public TransResult update(BaseUser user) {
    	user.setLastModifiedBy(getLoginName());
        TransResult transResult = new TransResult();
        
        String url = mesProperties.getUrl() + "/imes-provider/system/authority/user/update/wms";
        //Mes修改
		UserMes userUpate = new  UserMes();
		userUpate.setAccount(user.getLoginName());
		userUpate.setPersonCode(user.getLoginName());
		userUpate.setPersonName(user.getUserName());
		userUpate.setMarkAble(user.getLoginFlag());//		0：无效 1：有效
		//userUpate.setRemark("WMS新增");
		userUpate.setUpdateUser(getLoginName());
		userUpate.setUpdateUserName(getUserName());
		userUpate.setPassword(user.getPassword());

		
//		调mes新增接口
		HandResp handResp = mesInterfaceService.publicWSResp(url, MediaType.APPLICATION_JSON_TYPE, JSON.toJSONString(userUpate));
		if(handResp.getCode() != null && handResp.getCode().equals("0")){
			transResult.setCode(handResp.getCode());
			transResult.setMsg(handResp.getMsg());
	        return transResult;
		}else{
			Resp resp = userService.update(user);
	        transResult.setCode(resp.getCode());
	        transResult.setMsg(resp.getMsg());
	        return transResult;
		}
    }
    /**
     * @Description: 删除(批量)
     * @author zxcq0
     * @date 2017/3/2 15:09
     * @param
     * @return
     */
    @RequestMapping(value = "/d", method = RequestMethod.POST)
    public TransResult delete(@RequestParam(name = "userIds") List<String> userIds) {
        TransResult transResult = new TransResult();
        
        String url = mesProperties.getUrl() + "/imes-provider/system/authority/user/delete/wms";
        
        if(userIds.get(0)==null||userIds.get(0).equals("")){
        	transResult.setCode("0");
			transResult.setMsg("用户id为空，请传入");
	        return transResult;
        }else{
        	BaseUser user = userService.queryById(userIds.get(0));
        	if(user.getLoginName()==null||user.getLoginName().equals("")){
        		transResult.setCode("0");
    			transResult.setMsg("该用户根据ID搜索不到");
    	        return transResult;
        	}
        	String loginName=user.getLoginName();
        	//Mes修改
     		UserMes userUpate = new  UserMes();
     		
     		userUpate.setAccount(loginName);

//     		调mes新增接口
     		HandResp handResp = mesInterfaceService.publicWSResp(url, MediaType.APPLICATION_JSON_TYPE, JSON.toJSONString(userUpate));
     		if(handResp.getCode() != null && handResp.getCode().equals("0")){
     			transResult.setCode(handResp.getCode());
     			transResult.setMsg(handResp.getMsg());
     	        return transResult;
     		}else{
             
             Resp resp = userService.deleteBatch(userIds);
             transResult.setCode(resp.getCode());
             transResult.setMsg(resp.getMsg());
     		}
             return transResult;
        }
        
    }
    
//    /**
//     * @throws ParseException  
//    * @Title: transBaseUser 
//    * @Description: 时间范围的转换
//    * @author zhangxu 
//    * @2017年4月5日:2017年4月5日:下午3:21:53
//    * @param @param condition    
//    * @return void    
//    * @throws 
//    */
//    private void transBaseUser(BaseUser condition) throws ParseException {
////    	创建时间
//    	String gmtCreateStr = condition.getGmtCreateStr();
//		if (CheckEmptyUtil.isNotEmpty(gmtCreateStr)) {
//			FromToObj obj = CommonUtils.getFromTo(gmtCreateStr, Constant.FROM_TO_DATE);
//			if (obj.getDate()!=null) {
//				condition.setGmtCreate(obj.getDate());
//			}else {
//				if (obj.getFromDate()!=null) {
//					condition.setGmtCreateMin(obj.getFromDate());
//				}
//				if (obj.getToDate()!=null) {
//					condition.setGmtCreateMax(obj.getToDate());
//				}
//			}
//		}
////		更新时间
//		String gmtModifiedStr = condition.getGmtModifiedStr();
//		if (CheckEmptyUtil.isNotEmpty(gmtModifiedStr)) {
//			FromToObj obj = CommonUtils.getFromTo(gmtModifiedStr, Constant.FROM_TO_DATE);
//			if (obj.getDate()!=null) {
//				condition.setGmtModified(obj.getDate());
//			}else {
//				if (obj.getFromDate()!=null) {
//					condition.setGmtModifiedMin(obj.getFromDate());
//				}
//				if (obj.getToDate()!=null) {
//					condition.setGmtModifiedMax(obj.getToDate());
//				}
//			}
//		}
//	}

    /**
     * @Description: 新翻页修改
     * @author zxcq0
     * @date 2017/3/9 15:38
     * @param
     * @return
     */
    @PostMapping("list")
    public TransResult queryList(@RequestParam(name = "page", defaultValue = "1") int page,
                                 @RequestParam(name = "rows", defaultValue = "10") int rows,
                                 BaseUser condition) {
        condition.setCurrentPage(page);
        condition.setPageSize(rows);
        TransResult result = new TransResult();
//        获取翻页信息
        TurnPageInfo pageInfo = userService.queryListPageInfo(condition);
        Pager<BaseUser> pager = new Pager<>();
        pager.setPage(page);
        pager.setRows(rows);
//        真正查询
        if (pageInfo.getTotalCount()>0){
            List list = userService.queryList(condition);
            pager.setTotalPage(pageInfo.getTotalPage());
            pager.setTotalCount((long)pageInfo.getTotalCount());
            pager.setRecords(list);

        }
        result = success(pager);
        return result;
    }

    /**
     * @Description: 增加用户的角色
     * @author zxcq0
     * @date 2017/3/3 11:07
     * @param
     * @return
     */
    @RequestMapping(value="/resrole/c",method= RequestMethod.POST)
    public TransResult addUserResrole(@RequestBody List<BaseUserResroleKey> userResroleKeys) {
        TransResult transResult = new TransResult();
        Resp resp = userResroleService.addResroles(userResroleKeys);
        transResult.setCode(resp.getCode());
        transResult.setMsg(resp.getMsg());
        return transResult;
    }
    /**
     * @Description: 删除用户的角色
     * @author zxcq0
     * @date 2017/3/3 13:33
     * @param
     * @return
     */
    @RequestMapping(value="/resrole/d",method= RequestMethod.POST)
    public TransResult delUserResrole(@RequestBody List<BaseUserResroleKey> userResroleKeys) {
        TransResult transResult = new TransResult();
        Resp resp = userResroleService.deleteResroles(userResroleKeys);
        transResult.setCode(resp.getCode());
        transResult.setMsg(resp.getMsg());
        return transResult;
    }
    
    /**
     * @Description: 更新某个用户拥有的角色（用户分配角色，先删除角色关系，再加入角色关系）
     * @author lt
     * @date 2017/3/17 10:00
     * @param
     * @return
     */
    @RequestMapping(value="/usrrole/c",method= RequestMethod.POST)
    public TransResult updateUsrRoleRelation(@RequestBody Transfer<String, BaseUserResroleKey> transfer) {
        TransResult transResult = new TransResult();
        Resp resp = userResroleService.updateUsrRoleRelation(transfer.getConditions(), transfer.getRecords());
        transResult.setCode(resp.getCode());
        transResult.setMsg(resp.getMsg());
        return transResult;
    }
    
    /**
     * @Description: 获取用户的角色列表
     * @author zxcq0
     * @date 2017/3/6 10:53
     * @param
     * @return
     */
    @RequestMapping(value = "/{id}/resrole", method = RequestMethod.POST)
    public TransResult getUserResroles(@PathVariable String id) {
        TransResult transResult = new TransResult();
        transResult.setCode(Constant.SUCCESS);
        BaseUserResroleKey condition = new BaseUserResroleKey();
        condition.setUserId(id);
        List resroleIds = userResroleService.queryUserResroleIds(condition);
        transResult.setData(resroleIds);
        return transResult;
    }

    @PostMapping(value = "file")
    public TransResult testFile(@RequestParam("file") MultipartFile file){
        String fileId = "";
//        if (!file.isEmpty()){
//            log.info("------------start upload file-----------");
//            log.info(fastDFSConfig.getPrefix());
//            try {
//                fileId = FastDFSClientUtil.uploadFile(FastDFSClientUtil.BYTE_FILE,file.getBytes(),null,file.getOriginalFilename());
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
        TransResult result = new TransResult();
        result.setMsg(fileId);
        return result;
    }

    @GetMapping("all")
    public TransResult queryUserAll() {
        List<BaseUser> userList = userService.queryUserAll();
        return success(userList);
    }

    /** 
     * @Description: 查询用户的资源 
     * @Param:  
     * @return:  
     * @Author: zhangx
     * @Date: 2018/4/26 16:13
     */ 
    @PostMapping("resource/list")
    public TransResult list(@RequestParam(name = "page", defaultValue = "1") int page,
                            @RequestParam(name = "rows", defaultValue = "10") int rows,BaseUserResourceForm baseUserResourceForm) {
        Pager<BaseUserResourceForm> result = baseResourceService.findUserResList(page,rows,baseUserResourceForm);
        return success(result);
    }

    
}
